<template>
  <view class="page home-bg" :style="{ paddingTop: safeArea_top + 'px' }">
    <view class="banner">
      <u-swiper
        :list="list1"
        :indicator="false"
        imgMode="heightFix"
        indicatorMode="line"
        keyName="image"
        circular
        class=" "
        height="52vw"
        radius="10"
        @click="getSwiper"
      >
      </u-swiper>
    </view>
    <view class="product-wrapper content-p" v-if="!isNoWifi">
      <u-skeleton rows="10" :loading="loading" :title="false" rowsHeight="120">
      </u-skeleton>

      <view style="margin-top: 16px" v-if="indexTech.data.length > 0">
        <view class="indexTech_title">金牌技师</view>
        <scroll-view class="indexTech" scroll-x="true">
          <navigator
            class="item"
            v-for="(item, index) in indexTech.data"
            :url="`/bundle/pages/home/home?id=${item.id}`"
          >
            <view class="avatar">
              <image
                :src="`${item.avatar}?x-oss-process=image/resize,m_fill,quality,q_100,w_400,h_400`"
              >
              </image>
              <view>{{ item.realname }}</view>
            </view>

            <view class="distance"
              >距离<text>{{ fixdjl(item.distance) }}km</text></view
            >
          </navigator>
        </scroll-view>
      </view>
      <view class="indexTech_title" style="margin-top: 16px">服务项目</view>

      <navigator
        class="product-item flex-row"
        :key="i"
        v-for="(item, i) in productlList"
        :url="`/pages/details/index?id=${item.id}`"
        :render-link="false"
      >
        <view class="left-section flex-col">
          <view class="text-wrapper flex-col">
            <u--image
              :showLoading="true"
              :src="item.cover"
              width="200rpx"
              height="154rpx"
              radius="4"
              :fade="true"
              duration="450"
              :lazy-load="true"
              loadingIcon="photo"
            >
            </u--image>
          </view>
        </view>
        <view class="right-group flex-col">
          <view class="flex-row justify-bw">
            <text class="text_8">{{ item.name }}</text>
            <text class="text_10">超{{ item.sales }}人选择</text>
          </view>
          <view class="group_8 flex-row flex justify-between">
            <text class="stime">{{ item.duration }}分钟</text>
          </view>
          <view class="xz" @click.stop="showjishilist(item.id)">选择技师</view>

          <view class="group_9 flex-row group_10">
            <view class="left-group flex ane">
              <text class="text_18 price-font"
                ><text class="text_16">￥</text>{{ item.price }}</text
              >
              <text class="text_22 price-font1 tl"
                ><text class="text_20">￥</text>{{ item.original_price }}</text
              >
              <view
                style="display: inline-flex; color: #727272"
                class="text_22 flex ane"
              >
                <text class="text_14"></text>
              </view>
            </view>
          </view>
        </view>
      </navigator>
    </view>

    <view class="no-wifi" v-else>
      <image src="/static/no-wifi2.png" mode="widthFix" style="width: 300rpx" />
      <view class="fail">加载失败</view>
      <view class="tips">网络出了问题，重新试试吧</view>
      <view class="btn" @tap="reload">重新加载</view>
    </view>

    <u-overlay :show="show_code" @click="show_code = false">
      <view class="warp">
        <image :src="follow" mode="widthFix" style="width: 550rpx"></image>
      </view>
    </u-overlay>
    <u-overlay :show="show_q" @click="show_q = false">
      <view class="warp">
        <image
          :src="couponImg"
          mode="widthFix"
          style="width: 550rpx"
          @click="getcoupon"
        ></image>
      </view>
    </u-overlay>
    <u-popup
      :show="jishilist_show"
      mode="bottom"
      @close="jishilist_show = false"
      round="10"
      :closeable="true"
    >
      <view class="popindex">
        <selectTech :license="license"></selectTech>
      </view>
    </u-popup>

    <up-popup
      :show="authShow"
      mode="center"
      :closeOnClickOverlay="false"
      round="10"
    >
      <view
        style="
          width: 270px;
          height: 160px;
          padding: 30px 20px;
          text-align: center;
        "
      >
        <text style="font-weight: bold"
          >请允许应用使用定位权限，以便您使用商户相关功能。</text
        >
        <view
          style="
            display: flex;
            padding-top: 30px;
            justify-content: space-between;
          "
        >
          <view
            style="
              border: 1px solid #f0f0f0;
              padding: 8px 35px;
              border-radius: 20px;
            "
            @click="cancelAuth"
          >
            取消</view
          >
          <view
            style="
              background: #38987c;
              color: #fff;
              padding: 8px 35px;
              border-radius: 20px;
            "
            @click="confirmAuth"
            >确定</view
          >
        </view>
      </view>
    </up-popup>

    <up-popup
      :show="authGetTips"
      mode="top"
      :closeOnClickOverlay="false"
      round="14"
    >
      <view
        style="
          width: 100%;
          height: 200rpx;
          padding: 30px 20px 10px;
          display: flex;
          align-items: center;
        "
      >
        <view style="margin-right: 30rpx; display: flex; align-items: center">
          <up-icon name="map" size="30"></up-icon>
        </view>
        <view style="display: flex; flex-direction: column">
          <view style="font-weight: 500">位置权限使用说明</view>
          <view style="font-size: 26rpx"
            >根据您的位置信息为您推荐周边的技师服务</view
          >
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script>
import { HUAWEI } from "@/utils/enum.js";
import base from "@/config/baseUrl";
import selectTech from "./selectTech.vue";
import { checkLocationPermission } from "@/utils/openSettings.js";
import { requestAndroidPermission } from "@/js_sdk/wa-permission/permission.js";
let _this;
export default {
  components: {
    selectTech,
  },
  data() {
    return {
      HUAWEI,
      ladImg:
        "https://ryjdshop.oss-cn-beijing.aliyuncs.com/admin/202210/202210291824180187349.png",
      base: base,
      show_q: false,
      title: "",
      show: false,
      authShow: false,
      city: "北京市",
      weather: {
        type: "",
        low: "",
        high: "",
        date: "",
      },
      bgColor: {
        backgroundImage: "linear-gradient(to right, #31D081,#18B567)",
      },
      list1: [],
      page: 1,
      current: 0,
      total: null,
      productlList: [],
      loading: true,
      src: "https://codefun-proj-user-res-1256085488.cos.ap-guangzhou.myqcloud.com/61ab188e1f655f0011bbaece/61e7d9270c0e3200129ec72c/16425844604317986283.png",
      // "113.012546,28.199271"
      latitude: 106.587223769,
      longitude: 29.567061070386,
      initLocation: "",
      is_wxapp: true,
      show_code: false,
      name: "",
      wx_code: "",
      pid: "",
      tpid: "",
      showQuoun: false,
      follow: "",
      couponImg: "",
      is_coupon: 0,
      is_ios: 0,
      safeArea_top: 0,
      jishilist_show: false,
      indexTech: {
        show: false,
        data: [],
      },
      time: null,
      isNoWifi: false,
      authGetTips: false,
      license: null,
    };
  },
  onLoad() {
    this.license = uni.getStorageSync("app-license");
    const location = uni.getStorageSync("location");
    // console.log('uni.getSystemInfoSync().platform', uni.getSystemInfoSync().platform);
    if (uni.getSystemInfoSync().platform === "android") {
      var showAuthPopup = uni.getStorageSync("showAuthPopup");
      if (showAuthPopup === 1 || showAuthPopup === 2) {
        this.authShow = false;
      } else {
        this.authShow = true;
      }

      var tips = uni.getStorageSync("isNotAuth");
      var permissions = checkLocationPermission();
      if (permissions.fine || permissions.coarse) {
        console.log("已拥有定位权限");
        // uni.removeStorageSync("isNotLocationAuth")
      } else {
        if (tips && !location) {
          uni.showToast({
            duration: 5000,
            title: "由于您拒绝了定位权限。可能导致您无法正常使用商户相关功能。",
            icon: "none",
          });
        }
      }
    }
    //获取机型
    if (uni.getSystemInfoSync().platform == "ios") {
      this.is_ios = 1;
    }
    uni.getNetworkType({
      success: (res) => {
        if (res.networkType !== "none") {
          this.loadInit();
          this.isNoWifi = false;
        } else {
          // 没有网络
          this.isNoWifi = true;
        }
      },
    });
	
	const first_run = uni.getStorageSync("first_run")
	if(!first_run){
	   const first_run = uni.setStorageSync("first_run", 1)
	}
  },
  methods: {
    // 不授权
    cancelAuth() {
      this.authShow = false;
      uni.setStorageSync("isNotAuth", true);
      uni.setStorageSync("showAuthPopup", 1);
      uni.showToast({
        duration: 3000,
        title: "由于您拒绝了定位权限。可能导致您无法正常使用商户相关功能。",
        icon: "none",
      });
    },
    // 确认授权
    confirmAuth() {
      this.authShow = false;
      this.authGetTips = true;
      uni.setStorageSync("showAuthPopup", 2);
      uni.getLocation({
        type: "wgs84",
        geocode: true,
        highAccuracy: true,
        success: (res) => {
          // console.log("--------->>>", res);
          this.saveLocation(res.latitude, res.longitude);
        },
        complete: () => {
          this.authGetTips = false;
        },
      });
    },
    reload() {
      this.loading = true;
      uni.getNetworkType({
        success: (res) => {
          if (res.networkType !== "none") {
            this.isNoWifi = false;
            this.loading = true;
            this.loadInit();
          } else {
            // 没有网络
            this.isNoWifi = true;
          }
        },
      });
    },
    // 封装一下onload中的方法
    async loadInit() {
      _this = this;
      const safeArea = uni.getStorageSync("safeArea");
      this.safeArea_top = safeArea.top;

      uni.$u.sleep(500).then(() => {
        this.init();
        this.loading = false;
      });
      // 获取当前定位地址
      let address = uni.getStorageSync("address_info");
      if (address) {
        this.city = address.district ? address.district : address.city;
        this.loadIndexTech(address.latitude, address.longitude);
      }
      this.getInfo();
    },
    loadIndexTech(lat, lng) {
      _this.$http
        .post("api/technician/indexTech", {
          mlat: lat,
          mlng: lng,
        })
        .then((ret) => {
          _this.indexTech.data = ret;
        });
    },
    fixdjl(n) {
      return n.toFixed(1);
    },
    getInfo() {
      var new_people = uni.getStorageSync("new_people");
      if (new_people == 0 && !this.showQuoun && this.is_coupon == 1) {
        this.show_q = true;
      } else {
        this.show_q = false;
      }
    },
    getcoupon() {
      this.$http
        .post("api/coupon/newPeopleReceive")
        .then((res) => {
          uni.showToast({
            title: "领取成功！",
          });
          this.show_q = false;
        })
        .catch((err) => {
          this.show_q = false;
        });
    },
    getSwiper(e) {
		console.log("e==",e);
      if (e === 0) {
        plus.runtime.openWeb(this.list1[e].url);
        ("https://www.wenjuan.com/s/UZBZJvtJqvz/");
      } else if (e === 1 && this.license !== this.HUAWEI) {
        uni.navigateTo({
          url: "/bundle/pages/settled/settled",
        });
      } else {
        uni.navigateTo({
          url: "/bundle/pages/feedback/feedback",
        });
      }
    },
    async getConfig() {
      await this.$http.post("api/index/shareConfig").then((res) => {
        const {
          wx_code,
          name,
          share_title,
          share_content,
          logo,
          follow,
          couponImg,
          is_coupon,
        } = res;
        this.follow = follow;
        this.couponImg = couponImg;
        this.is_coupon = is_coupon;
        this.wx_code = wx_code;
        uni.setNavigationBarTitle({
          title: name,
        });
      });
    },
    async requestAndroidPermission(permisionID) {
      var result = await requestAndroidPermission(permisionID);
      return result;
      // var strStatus
      // if (result == 1) {
      //     strStatus = "已获得授权"
      // } else if (result == 0) {
      //     strStatus = "未获得授权"
      // } else {
      //     strStatus = "被永久拒绝权限"
      // }
    },
    getTips() {
      uni.showModal({
        title: "提示",
        content: "请开启定位获取附近技师!",
        confirmText: "确认",
        showCancel: false,
        success: function (res) {
          // 用户点击确认，跳转到设置页面
          // checkOpenGPSServiceByAndroid()
        },
      });
    },
    saveLocation(lat, lng) {
      this.$http
        .post("api/wechat/getMapAddress", {
          location: `${lat},${lng}`,
        })
        .then((address) => {
          let { ad_info, address: street } = address.result;
          let { location } = ad_info;
          ad_info.latitude = location.lat;
          ad_info.longitude = location.lng;
          ad_info.address = street;

          ad_info.lat = location.lat;
          ad_info.lng = location.lng;

          uni.setStorageSync("address_info", ad_info);
          this.city = ad_info.district ? ad_info.district : ad_info.city;
          this.loadIndexTech(location.lat, location.lng);
          uni.hideLoading();
          uni.setStorageSync("location", location);
        });
    },
    // 获取轮播图
    getBanner() {
      this.$http.post("api/index/index").then((res) => {
        if (this.license === this.HUAWEI) {
          this.list1 = res.filter((item) => item.id !== 111);
        } else {
          this.list1 = res;
        }
      });
    },
    // 获取首页列表数据
    getList() {
      this.$http
        .post("api/index/cityService", {
          page: this.page,
          orderBy: this.current,
          type: this.is_ios,
        })
        .then((res) => {
          let { list, total } = res;
          this.productlList.push(...list);
          this.total = total;
        });
    },
    init() {
      this.getBanner();
      this.getList();
    },
    onClickItem(e) {
      if (this.current !== e) {
        this.current = e;
        this.page = 1;
        this.productlList = [];
        this.total = null;
        this.getList();
      }
    },
    changeShow(e) {
      this.show = e;
    },
    showjishilist(jishiid) {
      uni.setStorageSync("order_info", {
        service_id: jishiid,
        spec_id: 0,
        coupon_id: 0,
      });
      this.jishilist_show = true;
    },
  },
  onNavigationBarButtonTap(e) {
    this.$refs.mpvueCityPicker.show();
  },
  onPullDownRefresh() {
    let _self = this;
    setTimeout(() => {
      uni.stopPullDownRefresh(); //停止当前页面下拉刷新
      this.page = 1;
      this.productlList = [];
      this.total = null;
      this.init();
    }, 1000);
  },
};
</script>

<style lang="scss">
@import "index.scss";
</style>
